//
//  ZFMenuCollectionLayout.m
//  components
//
//  Created by linzaifei on 2021/9/2.
//

#import "ZFMenuCollectionLayout.h"
@interface ZFMenuCollectionLayout()
@property(nonatomic,strong)NSMutableArray <UICollectionViewLayoutAttributes *>*attributes;
@property(nonatomic)CGSize contentSize; ///获取可以滚懂的范围
@end
@implementation ZFMenuCollectionLayout

-(NSInteger)getPage:(NSInteger)count{
    ///每页个数
    NSInteger number = self.row *self.column;
    if ((count % number) ==0) {
        return count/number;
    }
    return count/number +1;
}

- (void)prepareLayout{
    [self.attributes removeAllObjects];
    ///获取所有个数
    NSInteger count = [self.collectionView numberOfItemsInSection:0];
//    NSLog(@"%ld",count);
    ////判断可以分几页
    NSInteger page = [self getPage:count];
//    NSLog(@"%ld",page);
    ///获取滚动范围
    self.contentSize = CGSizeMake(page * CGRectGetWidth(self.collectionView.frame), CGRectGetHeight(self.collectionView.frame));
    
    ///UICollectionViewLayoutAttributes 重新赋值frame
    CGFloat x = self.sectionInset.left;
    CGFloat y = self.sectionInset.top;
    
    for (int i =0; i<page; i++) {
        for (int j = 0; j<self.column; j++) { ///列 4
            for (int k= 0; k<self.row; k++) { ///行 2
                NSInteger index = self.row*j+ k + (i*self.row*self.column);
                if (index>=count) return;
                NSIndexPath *path = [NSIndexPath indexPathForRow:index inSection:0];
                UICollectionViewLayoutAttributes *att = [UICollectionViewLayoutAttributes layoutAttributesForCellWithIndexPath:path];
                CGFloat offestX  = x + (index%self.column ) * (self.itemSize.width + self.minimumLineSpacing)+ i * CGRectGetWidth(self.collectionView.frame);
                CGFloat offestY = y+ ((index -i*self.row*self.column) /self.column ) * (self.itemSize.height  +self.minimumInteritemSpacing);
                att.frame = CGRectMake(offestX, offestY, self.itemSize.width, self.itemSize.height);
                [self.attributes addObject:att];
            }
        }
    }
}


-(CGSize)collectionViewContentSize{
    return self.contentSize;
}
-(NSArray<UICollectionViewLayoutAttributes *> *)layoutAttributesForElementsInRect:(CGRect)rect{
    NSMutableArray<UICollectionViewLayoutAttributes *> *visibledAttributes = [NSMutableArray array];
    [self.attributes enumerateObjectsUsingBlock:^(UICollectionViewLayoutAttributes * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        if (CGRectIntersectsRect(obj.frame, rect)) {
            [visibledAttributes addObject:obj];
        }
    }];
    return visibledAttributes;
}

#pragma mark --- getter
- (NSMutableArray<UICollectionViewLayoutAttributes *> *)attributes{
    if (!_attributes) {
        _attributes = [NSMutableArray array];
    }
    return _attributes;
}
@end
